<?php
class SP_Database_RecordSet
{
	private $fields=array();
	private $primary='id';
	private $table;
	private $base;
	private $result=array();
	
	public function __construct($table, $fields, $base)
	{
		$this->defineTable($table);
		$this->defineFields($fields);
		$this->defineDatabase($base);
	}
	
	public function defineDatabase($base)
	{
		$this->base=$base;
	}
	
	public function defineTable($name)
	{
		$this->table=$name;
	}
	
	public function definePrimary($name)
	{
		$this->primary=$name;
	}
	
	public function defineFields($fields)
	{
		$values = array_fill(0,count($fields),null);
		$this->fields = array_combine($fields, $values);
	}
		
	public function selectWhere($where)
	{
		$this->result=array();
		$base=$this->base->getReader();
		$query="SELECT * FROM `".$this->table."` WHERE $where";
		$base->query($query);
		while( $row=$base->fetchAssoc() )
		{
			$record=new SP_Database_ActiveRecord($this->table, array_keys($this->fields), $this->base);
			$record->definePrimary($this->primary);
			$record->fromRow($row);
			$this->result[$row[$this->primary]]=$record;
		}
		return $this->result;
	}
	
	public function selectAll()
	{
		$this->result=array();
		$base=$this->base->getReader();
		$query="SELECT * FROM `".$this->table."`";
		$base->query($query);
		while( $row=$base->fetchAssoc() )
		{
			$record=new SP_Database_ActiveRecord($this->table, array_keys($this->fields), $this->base);
			$record->definePrimary($this->primary);
			$record->fromRow($row);
			$this->result[$row[$this->primary]]=$record;
		}
		return $this->result;
	}
	
	public function getAssocField($field_name,$key_name=null)
	{
		if( empty($key_name) ) $key_name=$this->primary;
		$out=array();
		foreach($this->result as $record)
		{
			$out[$record->$key_name]=$record->$field_name;
		}
		return $out;
	}
}